package com.permgmt.service.impl;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.permgmt.entity.StockTransactionRecord;
import com.permgmt.mapper.StockTransactionRecordMapper;
import com.permgmt.service.IStockTransactionRecordService;
import com.permgmt.utils.StockUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 服务实现类
 *
 * @author LIAO
 * @since 2020-06-24
 */
@Service
public class StockTransactionRecordServiceImpl
	extends ServiceImpl<StockTransactionRecordMapper, StockTransactionRecord>
	implements IStockTransactionRecordService {

    @Override
    public List<StockTransactionRecord> pageList() {
	AbstractWrapper wrapper = new QueryWrapper();
	wrapper.orderByDesc("surplus_num/surplus_num");
	wrapper.orderByDesc("operation_time");
	List<StockTransactionRecord> recordList = baseMapper.selectList(wrapper);
	return recordList;
    }

    @Override
    public boolean sell(StockTransactionRecord record) {

	StockTransactionRecord recordOld = getById(record.getId());

	StockTransactionRecord sell = new StockTransactionRecord();
	sell.setCode(recordOld.getCode());
	sell.setName(recordOld.getName());
	sell.setOperation(0);
	sell.setPric(record.getPric());
	sell.setOperationTime(record.getOperationTime());
	sell.setSurplusNum(0);
	sell.setTotalNum(record.getSurplusNum());
	sell.setCost(StockUtil.cost(record.getPric() * record.getSurplusNum(), 0));

	recordOld.setSurplusNum(recordOld.getSurplusNum() - record.getSurplusNum());

	List<StockTransactionRecord> ls = new ArrayList<StockTransactionRecord>();

	ls.add(sell);
	ls.add(recordOld);

	return saveOrUpdateBatch(ls);
    }

    @Override
    public double statisticsProfit() {
	Double rest=baseMapper.statisticsProfit();
	return rest==null?0.0:rest;
    }
}
